// 保养记录页面
<template>
  <div>
    <div>
      <!-- QEMS-Quanta Equipment Monitoring System - [QSMC][BGM-SMT][1F] -->
      <div style="margin-bottom:8px;font-size:32px;text-align:center;">Module 保养记录信息</div>
      <el-form ref="form" :inline="true" size="small">
        <el-form-item label="ModuleSN" prop="moduleSN">
          <el-select v-model="form.moduleSN" placeholder="请选择,可搜索" filterable remote :clearable="true" :loading="loading"
            :remote-method="filterModuleSN">
            <el-option v-for="item in selectList" :key="item.id" :label="item.moduleSN" :value="item.moduleSN"></el-option>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page.sync="page" :page-sizes="[10, 20, 30, 50]" :page-size="limit"
              layout="total, sizes, prev, pager, next" :total="count"></el-pagination>
          </el-select>
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-select v-model="form.year" filterable placeholder="请选择">
            <el-option v-for="item in yearList" :key="item.value" :label="item.label" :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearchModuleSN">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="button">
      <!-- <el-button type="primary" size="small" @click="handleWeekAdd">新增周保养</el-button> -->
      <el-button type="primary" size="small" @click="handleMonthAdd">新增月保养</el-button>
      <el-button type="primary" size="small" @click="handleQuarterAdd">新增季保养</el-button>
      <!-- <el-button type="primary" size="small" @click="handleYearAdd">新增年保养</el-button> -->
    </div>
    <div class="tishi" v-if="showMessage">
      提示：
      <span class="message">无module信息！</span>
    </div>
    <!-- <el-table :data="weekTableData" style="width: 100%" :moduleer-cell-style="moduleerStyleEvent">
      <el-table-column label="周保养" moduleer-align="center" align="center">
        <el-table-column prop="recordId" label="recordId" width align="center"></el-table-column>
        <el-table-column prop="moduleId" label="moduleId" width align="center"></el-table-column> \>
        <el-table-column prop="moduleSN" label="序列号" width align="center"></el-table-column>
      后续再说 moduleType
         <el-table-column prop="moduleType" label="module类型" width align="center"></el-table-column> \>
        <el-table-column prop="year" label="年份" width align="center"></el-table-column>
        <el-table-column prop="mainteTypeOfNumInYear" label="周数" width align="center"></el-table-column>
        <el-table-column prop="mainteDate" label="周保养时间" width align="center"></el-table-column>
        <el-table-column prop="mainteEmpNo" label="保养员工" width align="center"></el-table-column>
        <el-table-column prop="mainteEmpName" label="保养员工姓名" width align="center"></el-table-column>
        <el-table-column prop="mainteMark" label="备注信息" width align="center"></el-table-column>
       暂时取消编辑修改
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="{row}">
            <el-button type="primary" size="small" @click="handleWeekEdit(row)">编辑</el-button>
          </template>
</el-table-column> \>
</el-table-column>
</el-table> -->
    <!-- :data="monthTableData" -->
    <el-table :data="mainteTableData" style="width: 100%" :moduleer-cell-style="moduleerStyleEvent"
      :span-method="mainteTableSpanMethod">
      <!-- label="Module保养" -->
      <el-table-column moduleer-align="center" align="center">
        <el-table-column prop="mainteType" label="保养类型" width align="center"></el-table-column>
        <el-table-column prop="moduleSN" label="序列号" width align="center"></el-table-column>
        
        <el-table-column prop="moduleType" label="模组类型" width align="center"></el-table-column>
        <el-table-column prop="year" label="年份" width align="center"></el-table-column>
        <el-table-column prop="mainteTypeOfNumInYear" label="月份/季度" width align="center"></el-table-column>
        <el-table-column prop="mainteDate" label="保养时间" width align="center"></el-table-column>
        <el-table-column prop="mainteEmpNo" label="保养员工" width align="center"></el-table-column>
        <el-table-column prop="mainteEmpName" label="保养员工姓名" width align="center"></el-table-column>
        <el-table-column prop="mainteMark" label="备注信息" width align="center"></el-table-column>
        <!-- 暂时取消编辑修改
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="{row}">
            <el-button type="primary" size="small" @click="handleMonthEdit(row)">编辑</el-button>
          </template>
        </el-table-column> -->
      </el-table-column>
    </el-table>
    <!-- <el-table :data="quarterTableData" style="width: 100%" :moduleer-cell-style="moduleerStyleEvent">
      <el-table-column label="季保养" moduleer-align="center" align="center">
        <el-table-column prop="moduleSN" label="序列号" width align="center"></el-table-column>
             后续再说 moduleType
        <el-table-column prop="moduleType" label="module类型" width align="center"></el-table-column> />
        <el-table-column prop="year" label="年份" width align="center"></el-table-column>
        <el-table-column prop="mainteTypeOfNumInYear" label="季度" width align="center"></el-table-column>
        <el-table-column prop="mainteDate" label="季保养时间" width align="center"></el-table-column>
        <el-table-column prop="mainteEmpNo" label="保养员工" width align="center"></el-table-column>
        <el-table-column prop="mainteEmpName" label="保养员工姓名" width align="center"></el-table-column>
        <el-table-column prop="mainteMark" label="备注信息" width align="center"></el-table-column>
      暂时取消编辑修改
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="{row}">
            <el-button type="primary" size="small" @click="handlequarterEdit(row)">编辑</el-button>
          </template>
        </el-table-column> />
      </el-table-column>
    </el-table> -->
    <!-- <el-table :data="yearTableData" style="width: 100%" :moduleer-cell-style="moduleerStyleEvent">
      <el-table-column label="年保养" moduleer-align="center" align="center">
        <el-table-column prop="moduleSN" label="序列号" width align="center"></el-table-column>
               后续再说 moduleType
        <el-table-column prop="moduleType" label="module类型" width align="center"></el-table-column> \>
        <el-table-column prop="year" label="年份" width align="center"></el-table-column>
        <el-table-column prop="mainteDate" label="年保养时间" width align="center"></el-table-column>
        <el-table-column prop="mainteEmpNo" label="保养员工" width align="center"></el-table-column>
        <el-table-column prop="mainteEmpName" label="保养员工姓名" width align="center"></el-table-column>
        <el-table-column prop="mainteMark" label="备注信息" width align="center"></el-table-column>
       暂时取消编辑修改
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="{row}">
            <el-button type="primary" size="small" @click="handleYearEdit(row)">编辑</el-button>
          </template>
        </el-table-column> \>
      </el-table-column>
    </el-table> -->
    <!-- 新增保养记录 -->
    <addDialog v-if="addDialogVisible" v-model="addDialogVisible" :dialog-title="dialogTitle"
      :item-info="moduleDialogProps" @refresh="handleRefresh"></addDialog>
    <!-- 编辑保养记录 -->
    <editDialog v-if="editDialogVisible" v-model="editDialogVisible" :dialog-title="dialogTitle"
      :item-info="editDialogProps" @refresh="handleRefresh"></editDialog>
  </div>
</template>
<script>
import dayjs from "dayjs";
import { getModuleSNSearch, getYearSelect } from '@/network/moduleSN'
import { getSnExists } from '@/network/moduleMaintain'
import { getWeekMaintain, getMonthMaintain, getQuarterMaintain, getYearMaintain, getAllMaintain } from '@/network/maintain'
import addDialog from './components/addDialog.vue';
import editDialog from './components/editDialog.vue';
export default {
  name: 'maintain',
  props: {},
  components: { addDialog, editDialog },
  data() {
    return {
      mainteTableData: [],
      weekTableData: [],
      monthTableData: [],
      quarterTableData: [],
      yearTableData: [],
      addDialogVisible: false,
      editDialogVisible: false,
      dialogTitle: '',
      moduleDialogProps: {
        moduleSN: ''
      },
      form: {
        moduleSN: '',
        year: Number(dayjs().format("YYYY")),
      },
      selectList: [],
      page: 1,
      limit: 20,
      count: 0,
      //搜索loading
      loading: false,
      yearList: [],
      editDialogProps: {},
      showMessage: false
    }
  },
  mounted() {


    this.getModuleSNSelectData()
    this.getYearSelectData()
    // 监听按键
    var code = ''
    var lastTime, nextTime // 上次时间、最新时间
    var lastCode, nextCode // 上次按键、最新按键
    document.onkeypress = (e) => {
      console.log(e);
      // 获取按键
      if (window.event) { // IE
        nextCode = e.keyCode
      } else if (e.which) { // Netscape/Firefox/Opera
        nextCode = e.which
      }
      // 如果触发了回车事件(扫码结束时间)
      if (nextCode === 13) {
        if (code.length < 3) return // 手动输入的时间不会让code的长度大于2，所以这里只会对扫码枪有
        this.codeFind(code) // 获取到扫码枪输入的内容，做别的操作
        code = ''
        lastCode = ''
        lastTime = ''
        return
      }
      nextTime = new Date().getTime() // 记录最新时间
      if (!lastTime && !lastCode) { // 如果上次时间和上次按键为空
        code += e.key // 执行叠加操作
      }
      // 如果有上次时间及上次按键
      if (lastCode && lastTime && nextTime - lastTime > 30) { // 当扫码前有keypress事件时,防止首字缺失
        code = e.key
      } else if (lastCode && lastTime) {
        code += e.key
      }
      lastCode = nextCode
      lastTime = nextTime
    }
  },

  methods: {
    handleSearchModuleSN() {
      this.getMainteTableData()
      /*  // 获取对应额周月季年
     this.getWeekData()
     this.getMonthData()
     this.getQuarterData()
     this.getYearData() */
    },
    mainteTableSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (!this.sortedTableData) {
        this.sortedTableData = this.mainteTableData;
      }
      const sortedTableData = this.sortedTableData;
      if (columnIndex === 0 || columnIndex === 1) {
        if (rowIndex > 0) {
          if ((columnIndex === 0 && row.mainteType === sortedTableData[rowIndex - 1].mainteType) ||
            (columnIndex === 1 && row.moduleSN === sortedTableData[rowIndex - 1].moduleSN)) {
            return {
              rowspan: 0,
              colspan: 0,
            }
          }
        }
        let rowspan = 1;
        for (let i = rowIndex + 1; i < sortedTableData.length; i++) {
          if ((columnIndex === 0 && row.mainteType === sortedTableData[i].mainteType) ||
            (columnIndex === 1 && row.moduleSN === sortedTableData[i].moduleSN)) {
            rowspan++;
          }
        }
        return {
          rowspan,
          colspan: 1,
        }
      }
    },
    async getModuleSNSelectData() {
      try {
        // const res = await getModuleSNSelect({ page: this.page, limit: this.limit })
        const res = await getModuleSNSearch({ page: this.page, limit: this.limit })
        this.selectList = res.data
        this.count = res.count
      } catch (error) {
        console.log(error);
      }
    },
    //下拉框搜索
    filterModuleSN(query) {
      this.loading = true
      this.form.moduleSN = query
      setTimeout(() => {
        this.loading = false
        this.searchModuleSN()
      }, 200);
    },
    async searchModuleSN() {
      try {
        const res = await getModuleSNSearch({ fuzzySNPart: this.form.moduleSN, page: this.page, limit: this.limit })
        this.count = res.count
        this.page = res.page
        this.limit = res.limit
        this.selectList = res.data
      } catch (error) {
        console.log(error);
      }
    },
    handleSizeChange(val) {
      this.limit = val;
      this.getModuleSNSelectData()
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getModuleSNSelectData()
    },
    async getYearSelectData() {
      try {
        const res = await getYearSelect()
        let obj = {};
        for (let key in res.data) {
          obj[key] = res.data[key];
        };
        this.yearList = Object.keys(obj).map(val => ({
          label: obj[val],
          value: val,
        }));
      } catch (error) {
        console.log(error);
      }
    },
    codeFind(code) {
      console.log(code + '扫描成功');
      let codes = code + ""
      this.moduleDialogProps.moduleSN = encodeURIComponent(codes)
      this.isSnExisit()
    },
    async isSnExisit() {
      try {
        const res = await getSnExists({ moduleSN: this.moduleDialogProps.moduleSN })
        if (res.data) {
          this.showMessage = false
          this.$router.push({
            path: `/spa/moduleMaintainRecordScan`,
            query: {
              moduleSN: this.moduleDialogProps.moduleSN,
            }
          })
        } else {
          this.showMessage = true
        }
      } catch (error) {
        console.log(error);
      }
    },
    async getWeekData() {
      try {
        const res = await getWeekMaintain({ moduleSN: this.form.moduleSN, year: dayjs().format("YYYY") })
        this.weekTableData = res.data
      } catch (error) {
        console.log(error);
      }
    },
    async getMonthData() {
      try {
        const res = await getMonthMaintain({ moduleSN: this.form.moduleSN, year: dayjs().format("YYYY") })
        this.monthTableData = res.data
      } catch (error) {
        console.log(error);
      }
    },
    async getMainteTableData() {
      try {
        const res = await getAllMaintain(this.form)
        this.mainteTableData = res.data
      } catch (error) {
        console.log(error);
      }
    },
    async getQuarterData() {
      try {
        const res = await getQuarterMaintain({ moduleSN: this.form.moduleSN, year: dayjs().format("YYYY") })
        this.quarterTableData = res.data
      } catch (error) {
        console.log(error);
      }
    },
    async getYearData() {
      try {
        const res = await getYearMaintain({ moduleSN: this.form.moduleSN, year: dayjs().format("YYYY") })
        this.yearTableData = res.data
      } catch (error) {
        console.log(error);
      }
    },
    handleAdd(mainteType) {
      const currDate = new Date();
      this.moduleDialogProps = {
        mainteDate: `${currDate.getFullYear()}-${currDate.getMonth() + 1}-${currDate.getDate()}`,
        // year: dayjs().format("YYYY"),
        mainteEmpNo: '',
        mainteEmpName: '',
        mainteMark: '',
        mainteType: mainteType
      }
      this.addDialogVisible = true
    },
    // 新增周保养
    handleWeekAdd() {
      this.dialogTitle = '新增周保养'
      this.handleAdd('week');
    },
    // 新增月保养
    handleMonthAdd() {
      this.dialogTitle = '新增月保养'
      this.handleAdd('month');
    },
    // 新增季保养
    handleQuarterAdd() {
      this.dialogTitle = '新增季保养'
      this.handleAdd('quarter');
    },
    handleYearAdd() {
      this.dialogTitle = '新增年保养'
      this.handleAdd('year');
    },
    // 页面刷新
    handleRefresh(data) { // 判断 mainteType 并更新
      if (data.recordUpdateType === 'add') {
        if (data.mainteType === 'year') {
          this.yearTableData.unshift(data)
        }
        else if (data.mainteType === 'quarter') {
          this.quarterTableData.unshift(data)
        }
        else if (data.mainteType === 'month') {
          this.monthTableData.unshift(data)
        }
        else if (data.mainteType === 'week') {
          this.weekTableData.unshift(data)
        }
      }
      else if (data.recordUpdateType === 'update') {
        if (data.mainteType === 'year') {
          if (!this.updateTableDatas(this.yearTableData, data)) {
            this.yearTableData.unshift(data)
          }
        }
        else if (data.mainteType === 'quarter') {
          if (!this.updateTableDatas(this.quarterTableData, data)) {
            this.quarterTableData.unshift(data)
          }
        }
        else if (data.mainteType === 'month') {
          if (!this.updateTableDatas(this.monthTableData, data)) {
            this.monthTableData.unshift(data)
          }
        }
        else if (data.mainteType === 'week') {
          if (!this.updateTableDatas(this.weekTableData, data)) {
            this.weekTableData.unshift(data)
          }
        }
      }
      //   this.getWeekData()
      //   this.getMonthData()
      //   this.getQuarterData()
      //   this.getYearData()
    },
    updateTableDatas(datas, updateData) {
      for (const d of datas) {
        if (d.moduleSN === updateData.moduleSN && d.year === updateData.year && d.mainteType === updateData.mainteType
          && d.mainteTypeOfNumInYear === updateData.mainteTypeOfNumInYear
        ) {
          d.mainteMark = updateData.mainteMark;
          d.mainteDate = updateData.mainteDate;
          d.mainteEmpName = updateData.mainteEmpName;
          d.mainteEmpNo = updateData.mainteEmpNo;

          // 无需强制更新
          // this.$forceUpdate();
          // this.$nextTick(() => {
          //     this.$forceUpdate();
          // });

          return true;
          break;
        }
      }

      return false;
    },
    // 周编辑
    handleWeekEdit(row) {
      console.log(row);
      this.dialogTitle = "编辑周保养"
      this.editDialogProps = { ...row }
      this.editDialogVisible = true
    },
    // 月编辑
    handleMonthEdit(row) {
      this.dialogTitle = "编辑月保养"
      this.editDialogProps = { ...row }
      this.editDialogVisible = true
    },
    // 季编辑
    handlequarterEdit(row) {
      this.dialogTitle = "编辑季保养"
      this.editDialogProps = { ...row }
      this.editDialogVisible = true
    },
    // 年编辑
    handleYearEdit(row) {
      this.dialogTitle = "编辑年保养"
      this.editDialogProps = { ...row }
      this.editDialogVisible = true
    },
    moduleerStyleEvent() {
      return { background: '#eef1f6', color: '#606266' }
    },
  }
}
</script>
<style scoped>
.title {
  background-color: #2f2e2e;
  color: white;
  font-size: 23px;
  line-height: 40px;
  height: 40px;
}

.ModuleSN {
  margin: 10px;
  font-weight: 500;
}

.button {
  margin-bottom: 10px;
}

.message {
  color: red;
}

.tishi {
  margin: 10px;
}
</style>